package com.future;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author xudong
 */
public class CompletableFutureDemo3 {

	public static void main(String[] args) throws InterruptedException {
		List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 6, 34, 35, 43);
		List<CompletableFuture<Integer>> futureList = list.stream()
				.map(value -> CompletableFuture.supplyAsync(() -> {
					System.out.println(Thread.currentThread() + " supplyAsync");
					return value;
				}))
				.collect(Collectors.toList());

		CompletableFuture<Integer> sumFuture = CompletableFuture
				.allOf(futureList.toArray(new CompletableFuture[0]))
				.whenComplete((v, e) -> {

				})
				.exceptionally(e -> {

					return null;
				})
				.thenApplyAsync(v -> {
					System.out.println(Thread.currentThread() + " thenApplyAsync");
					int sum = futureList.stream()
							.mapToInt(CompletableFuture::join)
							.sum();
					return sum;
				});
		// TimeUnit.SECONDS.sleep(1);
		System.out.println("-----------"  + sumFuture);
		Integer join = sumFuture.join();
		System.out.println("运行结果： " + join);
		System.out.println("-----------"  + sumFuture);
	}
}
